package com.design.reactor.stretchIO;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Set;

public class _3_NioClient2 {
	public static void client() throws IOException {
		SocketChannel sc = SocketChannel.open();
		sc.configureBlocking(false);
		sc.connect(new InetSocketAddress("127.0.0.1",8899));
		Selector s = Selector.open();
		sc.register(s, SelectionKey.OP_CONNECT);
		while(s.select()>0) {
			Set<SelectionKey> sks =s.selectedKeys();
			for (SelectionKey sk: sks) {
				SocketChannel client =(SocketChannel)sk.channel();
				final ByteBuffer bb= ByteBuffer.allocate(1024);
				if(sk.isConnectable()) {
					if(client.isConnectionPending()) {
						client.finishConnect();
						bb.put( ("to send server content").getBytes() );
						bb.flip();
						client.write(bb);

						ExecutorService es = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
						es.execute(()-> {
								bb.clear();
								try(
									InputStreamReader input =new InputStreamReader(System.in);
									BufferedReader br =new BufferedReader(input);
								){
									bb.put(br.readLine().getBytes());
									bb.flip();
									client.write(bb);
								}catch (Exception ignored) {

								}
						});
						client.register(s, SelectionKey.OP_READ);
					}

				}else if(sk.isReadable()) {
					bb.clear();
					int count = client.read(bb);
					bb.flip();
					if(count>0) {
						String rm= new String(bb.array(),0,count);
						System.out.println(rm);
					}

				}
				sks.remove(sk);
			}
		}
	}
	public static void main(String[] args) throws IOException {
		for (int i = 0; i < 1; i++) {
			new Thread(()->{
				try { client(); } catch (IOException e) { e.printStackTrace(); }
			}) .start();

		}

	}
}
